<?php
/**
 * 
 */
namespace app\home\controller\account;

use app\home\controller\Base;

class Handle extends Base
{

	private $params;
	private $account;

	public function __construct(){
		parent::__construct();
		// token验证
		if(false == Base::checkToken()){
			$this->error('token error!');
		}
		// 参数去token
		$params = $this -> request -> post();
		unset($params['token']);
		$this->params = $params;
		// 用户账户
		$this->account = $this->memberAccount();
	}

	/**
	 * 提交会员转账
	 * @return [type] [description]
	 */
	public function transfer(){
		// 总开关
		$switch = model('option')::getOne('transfer_switch');
		if(!$switch){
			$this->error('转账功能已经关闭，请联系管理员');
		}

		$params = $this->params;
		$validate = $this->validate($params,'Operate.home_transfer');
		if(true!==$validate){
			$this->error($validate);
		}

		$targetMid = strtoupper($params['target']);
		$targetUid = model('member')->where(['mid'=>$targetMid])->value('id');

		$coinId = $params['coin_id'];
		$amount = $params['amount'];
		$message = isset($params['message'])?$params['message']:'';

		$memberModel = model('member');

		// 获取转账配置
		$configData = model('coin_config')::coinConfigByType(__FUNCTION__);
		// 转账货币类型是否存在于设置中
		if(!in_array($coinId,array_column($configData, 'coin_id'))){
			$this->error('该货币类型不允许转账');
		}
		// 获取当前货币转账配置
		$config = array_combine(array_column($configData,'coin_id'), $configData)[$coinId];
		// 余额判断
		$beforeAmount = $this->account[$coinId]['amount'];

		if($beforeAmount-$amount<0){
			$this->error('操作失败，账户'.$config['coin_name'].'不足');
		}

		// 转账操作记录
		$operate = [
			'uid' => UID,
			'target' => $targetUid,
			'coin_id' => $coinId,
			'amount' => $amount,
			'message' => $message
		];

		$operateModel = model('operate_transfer');
		$operateModel->save($operate);
		$operateId = $operateModel->getLastInsID();

		// 发布消息队列
		$action = [
			'operate_id' => $operateId,
			'uid' => UID,
			'action_name' => __FUNCTION__,
			'action_data' => serialize($operate),
		];
		model('action')->save($action);

		// 处理消息队列
		$action = new \app\common\query\Action(UID,'transfer');
		$action->deal();

		$this->success('转账提交成功');
	}

	/**
	 * 提交货币转换
	 * @return [type] [description]
	 */
	public function convert(){
		// 总开关
		$switch = model('option')::getOne('convert_switch');
		if(!$switch){
			$this->error('功能已经关闭，请联系管理员');
		}

		$params = $this->params;
		$validate = $this->validate($params,'Operate.home_convert');
		if(true!==$validate){
			$this->error($validate);
		}

		$coinId = $params['coin_id'];
		$convert_coin_id = $params['convert_coin_id'];
		$amount = $params['amount'];
		
		// 获得配置
		$configData = model('coin_config')::convertCoinConfig();
		if(!isset($configData[$coinId])){
			$this->error('该货币类型不允许被转换');
		}
		// 该货币的转换配置
		$convertConfig = $configData[$coinId];
		$convertConfigTarget = $convertConfig['target'];
		$convertConfigTarget = array_combine(array_column($convertConfigTarget,'convert_coin_id'),$convertConfigTarget);
		if(!isset($convertConfigTarget[$convert_coin_id])){
			$this->error($convertConfig['coin_name'].'不允许转成目标货币类型');
		}

		// 原货币转目标货币配置
		$config = $convertConfigTarget[$convert_coin_id];
		// 转换金额计算
		$final_amount = $amount*$config['config']/100;
		// 余额判断
		$beforeAmount = $this->account[$coinId]['amount'];
		if($beforeAmount-$amount<0){
			$this->error('操作失败，账户'.$config['coin_name'].'不足');
		}

		// 转换操作记录
		$operate = [
			'uid' => UID,
			'convert_coin_id' => $convert_coin_id,
			'coin_id' => $coinId,
			'amount' => $amount,
		];

		$operateModel = model('operate_convert');
		$operateModel->save($operate);
		$operateId = $operateModel->getLastInsID();

		// 发布消息队列
		$action = [
			'operate_id' => $operateId,
			'uid' => UID,
			'action_name' => __FUNCTION__,
			'action_data' => serialize($operate),
		];
		model('action')->save($action);

		// 处理消息队列
		$action = new \app\common\query\Action(UID,'convert');
		$action->deal();

		$this->success('货币转换提交成功');

	}
	/**
	 * 提交充值申请
	 * @return [type] [description]
	 */
	public function charge(){
		// 总开关
		$switch = model('option')::getOne('charge_switch');
		if(!$switch){
			$this->error('功能已经关闭，请联系管理员');
		}

		$params = $this->params;
		// 验证器
		$result = $this->validate($params,'Operate.home_charge');
		if(true!==$result){
			$this->error($result);
		}
		$coinId = $params['coin_id'];
		$amount = $params['amount'];

		// 获取配置，判断充值货币类型
		$configData = model('coin_config')::coinConfigByType(__FUNCTION__);
		// 获取当前货币提现配置
		$config = array_combine(array_column($configData,'coin_id'), $configData)[$coinId];
		// 充值货币类型是否存在于设置中
		if(!in_array($coinId,array_column($configData, 'coin_id'))){
			$this->error($config['coin_name'].'不允许充值');
		}
		
		// 充值金额计算
		$final_amount = $amount*$config['config']/100;

		// 充值操作记录
		$record = [
			'uid' => UID,
			'coin_id' => $coinId,
			'amount' => $amount,
			'bank_name' => $params['bank_name'],
			'bank_address' => $params['bank_address'],
			'bank_card' => $params['bank_card'],
			'owner' => $params['owner'],
			'operate_time' => strtotime($params['operate_time']),
		];
		model('operate_charge')->save($record);

		$this->success('充值申请提交成功');
	}

	/**
	 * 提交提现申请
	 * @return [type] [description]
	 */
	public function withdraw(){
		// 总开关
		$switch = model('option')::getOne('withdraw_switch');
		if(!$switch){
			$this->error('功能已经关闭，请联系管理员');
		}
		// 提现日期判断
		$withdraw_days = \app\common\model\Option::getOne('withdraw_days');
		$withdraw_arr = explode(',',ltrim($withdraw_days,','));
		if(!in_array(intval(date('d')),$withdraw_arr)){
			$this->error('请在提现日期提现'.$withdraw_days);
		}

		$params = $this->params;
		// 验证器
		$result = $this->validate($params,'Operate.home_withdraw');
		if(true!==$result){
			$this->error($result);
		}
		
		$bankCardId = $params['bank_card'];
		$coinId = $params['coin_id'];
		$amount = $params['amount'];

		// 获取配置，判断提现货币类型
		$configData = \app\common\model\CoinConfig::coinConfigByType(__FUNCTION__);
		// 获取当前货币提现配置
		$config = array_combine(array_column($configData,'coin_id'), $configData)[$coinId];
		// 提现货币类型是否存在于设置中
		if(!in_array($coinId,array_column($configData, 'coin_id'))){
			$this->error($config['coin_name'].'不允许提现');
		}

		// 获取银行卡数据
		$bankCard = model('member_bank_card')->memberBankCard(UID,$bankCardId);
		if(!$bankCard){
			$this->error('所选银行卡不存在！');
		}

		// 提现金额计算
		$final_amount = $amount*$config['config']/100;
		// 余额判断
		$beforeAmount = $this->account[$coinId]['amount'];
		if($beforeAmount-$amount<0){
			$this->error('操作失败，账户'.$config['coin_name'].'不足');
		}

		$memberCoinModel = model('member_coin');

		$memberCoinModel -> startTrans();
		try{
			// 扣除对应货币金额
			$memberCoinModel -> where(['uid'=>UID,'coin_id'=>$coinId])->setDec('amount',$amount);
			$this->account = $this->memberAccount();
			$afterAmount = $this->account[$coinId]['amount'];

			// 新增操作记录
			$record = [
				'uid' => UID,
				'coin_id' => $coinId,
				'amount' => $amount,
				'bank_name' => $bankCard['bank_name'],
				'bank_address' => $bankCard['bank_address'],
				'bank_card' => $bankCard['bank_card'],
				'owner' => $bankCard['owner'],
			];
			$operateModel = model('operate_withdraw');
			$operateModel->save($record);
			$operateId = $operateModel->getLastInsID();

			// 资金变动记录
			$coin_record = [
                'operate_id' => $operateId,
                'uid' => UID,
                'coin_id' => $coinId,
                'amount' => $amount,
                'operate' => 'withdraw',
                'before_amount' => $beforeAmount,
                'after_amount' => $afterAmount,
                'remark' => '提现'.$amount.'【'.$config['coin_name'].'】',
                'flag' => 'dec'
            ];
            model('member_coin_record') -> save($coin_record);

			$memberCoinModel->commit();
		}catch(\Exception $e){
			$memberCoinModel -> rollback();
			$this->error($e->getMassage());
		}
		$this->success('提现申请提交成功');
	}

	private function memberAccount(){
		$model = model('member_coin');
		$memberAccount = $model -> where(['uid'=>UID])->select();
		foreach($memberAccount as &$account):
			$account=$account->toArray();
		endforeach;
		return array_combine(array_column($memberAccount,'coin_id'),$memberAccount);
	}

}